<template>
  <div class="tags-container">
    <el-tag
        v-for="(item, index) in tagsValue"
        :key="item.path.name"
        :closable="item.authName !== '首页'"
        :effect="activeTag(item) ? 'dark' : 'plain'"
        @click="changeMenu(item)"
        @close="handleClose(item, index)"
        class="tags"
        size="small"
    >
      {{ item.authName }}
    </el-tag>
  </div>
</template>

<script setup>
import { computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useCounterStore } from '../stores/counters.js';

const store = useCounterStore();
const route = useRoute();
const router = useRouter();

// 标签数据处理
const tagsValue = computed(() => {
  return store.menuList.map(item => ({
    ...item,
    path: typeof item.path === 'string'
        ? { name: item.path }
        : item.path
  }));
});

// 激活状态判断
const activeTag = (item) => {
  return route.name === item.path.name;
};

// 点击标签跳转
const changeMenu = (item) => {
  router.push(item.path);
};

// 关闭标签处理
const handleClose = (closedItem, index) => {
  store.closeTag(closedItem);

  // 关闭当前激活标签时跳转逻辑
  if (closedItem.path.name === route.name) {
    const nextTag = tagsValue.value[index] || tagsValue.value[index - 1];
    if (nextTag) {
      router.push(nextTag.path);
    }
  }
};
</script>

<style scoped>
.tags-container {
  padding: 10px;
  background: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
}

.tags {
  margin: 0 5px;
  padding: 8px 12px;
  cursor: pointer;
  user-select: none;
}

.tags:hover {
  opacity: 0.85;
}
</style>
